const weexApi = weex.requireModule("WeexApi");
const weexFunction = weex.requireModule("WeexFunction");
import jhttps from "@/_js/https";

//模拟账户
const MockApis = [
  {"exchangeId":"4","exchangeName":"Binance","tradeFee":"0.001"},
  {"exchangeId":"3","exchangeName":"Huobi","tradeFee":"0.002"},
  {"exchangeId":"29","exchangeName":"OkexV5","tradeFee":"0.0015"},
  {"exchangeId":"30","exchangeName":"CoinTR","tradeFee":"0.002"},
  {"exchangeId":"33","exchangeName":"Gate","tradeFee":"0.001"},
  // {"exchangeId":"35","exchangeName":"Kucoin","tradeFee":"0.001"},
  // {"exchangeId":"36","exchangeName":"Bitget","tradeFee":"0.001"},
  {"exchangeId":"38","exchangeName":"Bingx","tradeFee":"0.001"},

  {"exchangeId":"37","exchangeName":"Bithumb","tradeFee":"0.001"}
  
  // {"exchangeId":"22","exchangeName":"MEXC","tradeFee":"0.002"}
  // {"exchangeId":"21","exchangeName":"Pcsex","tradeFee":"0.001"},
  // {"exchangeId":"23","exchangeName":"Hoo","tradeFee":"0.002"},
  // {"exchangeId":"24","exchangeName":"Jubi","tradeFee":"0.002"},
  // {"exchangeId":"25","exchangeName":"CoinEx","tradeFee":"0.002"},
  // {"exchangeId":"28","exchangeName":"BITKAN","tradeFee":"0.001"},
  // {"exchangeId":"5","exchangeName":"Okex","tradeFee":"0.0015"}, //2022.3.11 隐藏
];

//合约支持的交易所
const CExchanges = ['Binance', 'Huobi', 'OkexV5', 'CoinTR', 'Gate', 'Kucoin', 'Bitget', 'Bingx'];

//U本位交易所（合约账户直接拿USDT余额）
const ExchangesU = {'binance':1, 'okexv5':1, 'cointr':1, 'gate':1, 'kucoin':1, 'bitget':1, 'bingx':1};

export default {

  /********************************************** 判断方法*/
  //合约：ture-U本位交易所，false-币本位交易所
  isExchangeUSDT(name) {
    name = name.toLowerCase();
    return ExchangesU[name];
  },

  /********************************************** get方法*/
  /** 获取总资产*/
  getTotalAssets(callback){
    weexApi.getTotalAssets((assets)=>{
      callback(assets);
    });
  },
  
  /** 获取API列表
   * 
   * @param {String} state all:所有API YES:可用API NO:无用API
   * @param {String} type  all:所有账户 COIN:币本位合约 USDT:USDT合约
   * @param {String} exchanges  过滤交易所数组：交易所名称 或 交易所ID
   * @param {Function} callback 结果回调
   */
  getApis(state, type, exchanges, callback) {

    state = state ? state : 'all';
    type = type ? type : 'all';

    if (state == 'all') {

      weexApi.getApiAll((apis)=>{
        this.screensType(apis, type, exchanges, callback);
      });
    } else if (state == 'YES') {

      weexApi.getApis((apis)=>{
        this.screensType(apis, type, exchanges, callback);
      });
    } else if (state == 'NO') {
      
      weexApi.getNoApis((apis)=>{
        this.screensType(apis, type, exchanges, callback);
      });
    }
  },

  /** 获取指定API
   * @param {String} apiId
   * @param {String} state all:所有API YES:可用API NO:无用API
   * @param {Function} callback 结果回调
   */
  getApi(apiId, state, callback) {
    
    this.getApis(state, 'all', null, (apis)=>{

      for (let index = 0; index < apis.length; index++) {
        var api = apis[index];
        if (apiId == api.apiId) {
          callback(api);
          return;
        }
      }
      callback(null);
    });
  },

  /** 获取模拟API列表
   * 
   * @param {Function} callback 结果回调
   * @param {String} exchanges  过滤交易所数组：交易所名称
   */
  getMockApis(exchanges, callback) {
    this.screensExchange(MockApis, exchanges, (mockApis)=>{
      callback(mockApis);
    });
  },

  /** 获取指定模拟API
   * 
   * @param {String} exchange  交易所名称 或 交易所ID
   * @param {Function} callback 结果回调
   */
  getMockApi(exchange, callback) {
    
    this.screensExchange(MockApis, exchange, (mockApis)=>{
      var mockApi = mockApis.length ? mockApis[0] : null;
      callback(mockApi);
    });
  },

  /** 获取支持合约的交易所*/
  getCExchanges() {
    return CExchanges;
  },
  
  
  /********************************************** 辅助方法*/
  /** 同步所有API
   * 
   * @param {Function} success  成功回调
   * @param {Function} failure   成功失败回调
   */
  synchroApis(success, failure){
    weexApi.synchroApis(()=>{
      setTimeout(() => {
        success&&success();
      }, 3000);
    }, ()=>{
      failure&&failure();
    });
  },

  /** 同步指定API
   * 
   * @param {String} apiId
   * @param {Function} success  成功回调
   * @param {Function} failure   成功失败回调
   */
  synchroApi(apiId, success, failure){
    weexApi.synchroApi(apiId, ()=>{
      setTimeout(() => {
        success&&success();
      }, 3000);
    }, ()=>{
      failure&&failure();
    });
  },

  /** 同步API指定币（现货）
   * 
   * @param {String} apiId
   * @param {String} coin 同步币
   */
  synchroCoin(apiId, coin){
    
    this.getApi(apiId, 'all', (api)=>{
      if (!api) {
        return;
      }
      this.httpPublicKey(apiId, false, (key)=>{
        this.rsaApi(api, key, (rsa)=>{
          var param = {'apiData':rsa, 'symbol':coin}
          jhttps.post("assetsV2/synchronizationSingelCoinApi",param,true,(data) => {
            if (data.status == 200) {
              data = data.data;
              weexApi.changeApiCoin(data);
            }
          });
        });
      } ,(mag)=>{});
    });
  },

  /** 同步API指定币（合约）
   * 
   * @param {String} apiId
   * @param {String} contractId 同步币
   * @param {Function} contractType 合约类型
   */
  synchroCoinContract(apiId, contractId, contractType){

    this.getApi(apiId, 'all', (api)=>{
      if (!api) {
        return;
      }
      this.httpPublicKey(apiId, false, (key)=>{
        this.rsaApi(api, key, (rsa)=>{
          var param = {'apiData':rsa, 'contractId':contractId, 'contractType':contractType}
          jhttps.post("assetsV2/synchronizationSingelContractApi",param,true,(data) => {
            if (data.status == 200) {
              data = data.data;
              var dict = {};
              dict[apiId] = data;
              weexApi.changeApiCoin(dict);
            }
          });
        });
      } ,(mag)=>{});
    });
  },

  /** 添加Api冻结
   * @param {String} apiId 
   * @param {String} coin 币
   * @param {String} num 数量
   * @param {Function} callback 结果回调
   */
  addApiLock(apiId, coin, num, callback){
    weexApi.addApiLock(apiId, coin, num);
    setTimeout(() => {
      callback&&callback();
    }, 3000);
  },

  /** 添加Api策略持仓
   * @param {String} apiId 
   * @param {String} coin 币
   * @param {String} num 数量
   * @param {Function} callback 结果回调
   */
  addApiStrategy(apiId, coin, num, callback){
    weexApi.addApiStrategyAsset(apiId, coin, num);
    setTimeout(() => {
      callback&&callback();
    }, 3000);
  },
  
  /** 设置API手续费
   * 
   * @param {String} apiId 
   * @param {String} tradeFee 手续费
   * @param {Function} callback 结果回调
   */
  setApiTradeFee(apiId, tradeFee, callback) {

    weexApi.modifyTradeFee(apiId, tradeFee);
    setTimeout(() => {
      callback&&callback();
    }, 3000);
  },
  
  /** 修改备注
   * 
   * @param {String} apiId 
   * @param {String} name 
   * @param {Function} callback 结果回调
   */
  remarks(apiId, name, callback) {
    weexApi.remarks(apiId, name);
    setTimeout(() => {
      callback&&callback();
    }, 3000);
  },

  /** 删除API
   * 
   * @param {String} apiId 
   * @param {Function} callback 结果回调
   */
  deleteApi(apiId, callback) {
    weexApi.deleteApi(apiId);
    setTimeout(() => {
      callback&&callback();
    }, 3000);
  },

  /** 添加Api*/
  addApi(api, callback){
    weexApi.addApi(api);
    setTimeout(() => {
      callback&&callback();
    }, 4000);
  },
  
  /** 续期API
   * 
   * @param {String} apiId 
   */
  grantApi(api){
    weexApi.grantApi(api);
  },

  /** RSA加密Api
    * @param {JSON} api
    * @param {String} key 服务器公钥
    * @param {Function} callback 结果回调
    */
  rsaApi(api, key, callback) {

    if (api == null || api.apiId == '') {
      callback('');
      return;
    }

    var apiData = {'exchangeName':api.exchangeName, 
                   'apiId':api.apiId};
    for (let index = 0; index < api.param.length; index++) {
      var param = api.param[index];
      apiData[param.field] = param.value;
    }

    apiData = JSON.stringify(apiData);
    weexFunction.rsaEncrypt(apiData, key, (rsa)=>{
      callback(rsa);
    });
  },
  
  /******************************************* http*/
  /** HTTP 获取API加密公钥
   * 
   * @param {String} apiId apiID
   * @param {Boolean} serverType turn执行服务器  false资产服务器
   * @param {*} success 成功回调
   */
  httpPublicKey(apiId, serverType, success=(key)=>{}, failure=(msg)=>{}){

    if (apiId == null || apiId.length == 0) {
      success('');
      return;
    }
    
    var param = serverType ? {serverType:'strategy'} : {serverType:'accountServer'};
    jhttps.post("assetsV2/getPublicKey",param,true,(data)=>{
      if(data.status == 200){
        var key = data.data.publicKey;
        success&&success(key);
      } else {
        failure&&failure(data.msg);
      }
    });
  },

  /********************************************** 私有方法*/
  /** apis筛选类型
   * 
   * @param {String} type  all:所有账户 COIN:币本位合约 USDT:USDT合约
   * @param {String} exchanges  过滤交易所数组：交易所名称 或 交易所ID
   * @param {Function} callback 结果回调
   */
  screensType(apis, type, exchanges, callback) {

    if (type == 'all') {

      this.screensExchange(apis, exchanges, callback);
    } else if (type == 'COIN') {

      var screens = [];
      for (let index = 0; index < apis.length; index++) {
        var api = apis[index];
        if (api.swapAssets) {
          screens.push(api);
        }
      }
      this.screensExchange(screens, exchanges, callback);
    } else if (type == 'USDT') {

      var screens = [];
      for (let index = 0; index < apis.length; index++) {
        var api = apis[index];
        if (api.linerSwapAssets) {
          screens.push(api);
        }
      }
      this.screensExchange(screens, exchanges, callback);
    }
  },

  /** apis筛选交易所
   * 
   * @param {String} exchanges  过滤交易所数组：交易所名称 或 交易所ID
   * @param {Function} callback 结果回调
   */
  screensExchange(apis, exchanges, callback) {

    if (!exchanges || exchanges.length==0){
      callback(apis);
      return;
    }

    if (typeof exchanges == 'string'){
      exchanges = [exchanges];
    }

    var screens = [];
    for(let i = 0; i < apis.length; i++){
      var api = apis[i];
      for(let j = 0; j < exchanges.length; j++){
        var ex = exchanges[j].toLowerCase();
        if (api.exchangeName.toLowerCase() == ex ||
           api.exchangeId.toLowerCase() == ex){
            screens.push(api);
        }
      }
    }
    callback(screens);
  },
}